package com.xhwl.centiotdata.suppliersystem.virtualDevice;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.suppliersystem.dahuaIcc.GeneralDaHuaIccHandler;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class GeneralVirtualDeviceHandler {
    private static final Logger log = LoggerFactory.getLogger(GeneralDaHuaIccHandler.class);

    public JSONObject get(String api, Map<String, Object> params, Integer projectId, Integer productId, String ipAndPort, String loginName, String password, String clientId, String clientSecret) {
        if (ipAndPort == null) {
            log.error("【virtual device post】path:{};getToken fail!", api);
            return null;
        }
        if(params.get("id")!=null && StringUtils.isNotEmpty(params.get("id").toString()) ){
            api = api+params.get("id").toString();
        }
        StringBuffer pathBuffer = new StringBuffer()
                .append(ipAndPort)
                .append(api);
        return this.getWithAuth(pathBuffer.toString());
    }

    private JSONObject getWithAuth(String path) {
        String result = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put("ngrok-skip-browser-warning", "12345");
            result = HttpRequest.get(path).addHeaders(header).execute().body();
        } catch (HttpException e) {
            log.error("【virtual device get】path:{}; request failed!", path);
            e.printStackTrace();
            throw new ApplicationException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("【virtual device get】path:{};result is null!", path);
            throw new BusinessException();
        }
        log.info("【virtual device get】path:{};result:{}", path, result);
        return JSON.parseObject(result);
    }
}
